<?php





namespace app\shop\model;



use app\admin\model\ShopModel;
use app\admin\model\ShopOrderModel;
use app\admin\model\SysModel;
use app\crm\model\CouponProvideCustomer;
use app\crm\model\Customer;
use app\crm\model\CustomerAccount;
use app\crm\model\CustomerPrestockExit;
use app\crm\model\CustomerPrestockGoods;
use app\crm\model\FollowRecord;

use app\admin\model\Common;

use app\crm\model\ProductItem;
use app\crm\model\Service;
use app\crm\model\ServiceLog;
use app\crm\model\ShopGoods;
use app\crm\model\ShopOrderGoods;
use app\shop\model\ShopOrderGoodsOptionLog;

use Kingdee\Kingdee;

use think\facade\Db;

use think\model\concern\SoftDelete;

use app\common\traits\ActionRecordTrait;
use app\services\SendMsg;


/**

 * 订单模型

 * @package app\shop\model

 * @author LIU

 * @create 2021-10-01

 */

class Order extends Common

{

    use ActionRecordTrait;



    /**

     * 表名

     * @var string

     */

    protected $name = 'shop_order';

    protected $defaultSoftDelete = 0;



    /**

     * 获取sku信息

     * @return \think\model\relation\hasOne

     * @author SL

     * @create 2021-05-27 15:04

     */

    public function orderGoods()

    {

        return $this->hasOne(Goods::class,'id');

    }









    /**

     * 获取sku信息

     * @return \think\model\relation\hasOne

     * @author SL

     * @create 2021-05-27 15:04

     */

    public function getHouseList($request)

    {

        try {



            $request = $this->fmtRequest($request);

            $map     = $request['map'] ?? [];

            if(!$map){

                $this->error = '请传入会员id';

                return [];

            }

            $shop_id = $map['shop_id'] ?? 0;

            if(!$shop_id){

                $this->error = '请传入门店id';

                return [];

            }

            $market_id=Db::name('shop')->where('shop_id',$shop_id)->value('market_id');

            $list=Db::name('house_code')->where('market_id',$market_id)->field('id,house_code_name,house_code')->select();

            $data              = [];

            $data['list']      = $list ?? [];

            return $data;

        }catch (\Exception $e) {

            $this->error = $e->getMessage();

            return [];

        }



    }





    /**

     * 获取销售政策列表

     * @return array

     * @author SL

     * @create 2021-06-1

     */

    public function getSaleList()

    {

        try {

            $list = Db::name('policy')->where('status',1)->select();

            $data              = [];

            $data['list']      = $list ?? [];

            return $data;

        }catch (\Exception $e) {

            $this->error = $e->getMessage();

            return [];

        }

    }


    /**

     * 获取订单列表

     * @param  array $request 请求参数

     * @return array

     * @author SL

     * @create 2021-06-1

     */

    public function getDataList($request)

    {

        try {

            $userId  = $request['user_id'] ?? 0;

            $shopIds= $request['shopIds'] ?? '';

            $person_shop_id = $request['person_shop_id']??0; //当前登陆人所属门店id
            $admin_user_id = $request['admin_user_id']??0;//当前登陆人id

            $request = $this->fmtRequest($request);

            $map     = $request['map'] ?? [];

            $where   = [];

            $id = isset($map['id']) && $map['id'] ? $map['id'] : [];
            if ($id) {
                if (!is_array($id)) {
                    $id = [$id];
                }
                array_push($where, ['o.id', 'in', $id]);
            }

            array_push($where, ['o.status', '<>', 4]);//排查已作废的

            $uid      = isset($map['uid']) && $map['uid'] ? trim($map['uid']) : ''; // 会员id

            $shop_id      = isset($map['shop_id']) && $map['shop_id'] ? trim($map['shop_id']) : ''; // 门店id

            $noValue      = isset($map['no_value']) && $map['no_value'] ? trim($map['no_value']) : ''; // 单号

            $consignee = isset($map['consignee']) && $map['consignee'] ? trim($map['consignee']) : ''; // 客户名称

            $status       = isset($map['status']) && intval($map['status']) ? intval($map['status']) : '-1'; // 订单状态

            $start_time = isset($map['start_time']) && $map['start_time'] ? strtotime(date($map['start_time'])) : 0;

            $end_time = isset($map['end_time']) && $map['end_time'] ? strtotime(date($map['end_time'] . ' 23:59:59')) : 0;

            $business_type    = isset($map['business_type']) && intval($map['business_type']) ? intval($map['business_type']) : 0; // 订单状态

            $order_type       = isset($map['order_type']) && intval($map['order_type']) ? intval($map['order_type']) : 0; // 订单状态

            $low_total = isset($map['low_total']) && $map['low_total'] ? $map['low_total']: 0;//销售金额区间搜索最小值

            $large_total =  isset($map['large_total']) && $map['large_total'] ? $map['large_total']: 0;//销售金额区间搜索最大值

            $shop_name = isset($map['shop_name']) && $map['shop_name'] ? trim($map['shop_name']) : ''; // 门店名称

            // 获取客户数据权限 的客户名称

            if ($shopIds) {
                array_push($where, ['o.shop_id', 'in', $shopIds]);
            }
            if ($uid) {
                //会员id搜索
                array_push($where, ['o.uid', '=', $uid]);
            }
            if ($shop_id) {
                //门店id搜索
                array_push($where, ['o.shop_id', '=', $shop_id]);
            }

            if ($shop_name) {
                //门店名称搜索
                array_push($where, ['o.shop_name', 'like', '%'.$shop_name.'%']);
            }

            if ($consignee) {
                // 客户名称搜索
                array_push($where, ['o.consignee', 'like', '%'.$consignee.'%']);
            }

            if ($status != -1) {
                array_push($where, ['o.status', '=', $status]);

            }

            if ($noValue) {
                array_push($where, ['o.order_no', '=', $noValue]);

//                $noType == 2 && array_push($where, ['o.king_num', '=', $noValue]);

//                $noType == 3 && array_push($where, ['o.king_send_no', '=', $noValue]);

//                $noType == 4 && array_push($where, ['o.king_sale_no', '=', $noValue]);

            }

            // 时间
            if($start_time && $end_time) {
                array_push($where, ['o.deal_time', 'between', "$start_time,$end_time"]);
            }

            if ($business_type) {
                //业务类型搜索
                array_push($where, ['o.business_type', '=', $business_type]);
            }

            if ($order_type) {
                //订单类型搜索
                array_push($where, ['o.order_type', '=', $order_type]);
            }

            if ($low_total && !$large_total) {
                array_push($where, ['o.order_amount', 'egt', $low_total]);
            }

            if (!$low_total && $large_total) {
                array_push($where, ['o.order_amount', 'elt', $large_total]);
            }

            if ($low_total && $large_total) {
                array_push($where, ['o.order_amount', 'between', "$low_total,$large_total"]);

            }

            $sqlQuery = $this->alias('o')

                ->where($where);

            $dataCount  = $sqlQuery->count();

            $sum_amount=0;



            if ($dataCount) {

                $sum_amount  = $sqlQuery->sum('o.order_amount');

                // 订单列表

                $field = ['o.id', 'o.order_no','o.is_lock','o.business_type','o.order_type','o.king_status', 'o.sale_name', 'o.consignee',

                    'o.goods_price','o.order_amount','o.status','o.shop_name','o.create_time','o.shop_id','o.deal_time','c.king_no'];

                $list = $sqlQuery->field($field)

                    ->join('customer c', 'o.uid = c.id')

                    ->limit(($request['page'] - 1) * $request['limit'], $request['limit'])

                    ->order('id DESC')

                    ->select()->toArray();

                if ($list) {
                    $order_type = [
                        0=>'',
                        1=>'初诊',
                        2=>'复诊',
                        3=>'再消费',
                        4=>'诊疗',
                        5=>'其他',
                    ];
                    $businessType = Db::name('customer_balance_category')->column('name','id');
                    foreach($list as &$v){
                        $v['order_type'] =  isset($order_type[$v['order_type']])?$order_type[$v['order_type']]:'';


                        $v['business_type']=isset($businessType[$v['business_type']])?$businessType[$v['business_type']]:'';

                        $v['deal_time']=date('Y-m-d', $v['deal_time']);

                        switch ($v['king_status']) {
                            case '1':
                                $v['king_status_msg'] = '已下推';
                                break;
                            case '2':
                                $v['king_status_msg'] = '下推失败';
                                break;
                            case '5':
                                $v['king_status_msg'] = '登录失败';
                                break;
                            default:
                                $v['king_status_msg'] = '暂未下推';
                                break;
                        }

                        switch ($v['status']) {
                            case '1':
                                $v['status_msg'] = '已支付';
                                break;
                            case '2':
                                $v['status_msg'] = '已下推';
                                break;
                            case '3':
                                $v['status_msg'] = '已评价';
                                break;
                            case '4':
                                $v['status_msg'] = '已作废';
                                break;
                            default:
                                $v['status_msg'] = '待审核';
                                break;
                        }

                    }

                }

            }



            $permission = get_user_permission_menu($userId,'order_list_tag');



            $data              = [];

            $data['menu_list'] = $permission ? $permission : [];

            $data['list']      = $list ?? [];

            $data['dataCount'] = $dataCount ?? 0;

            $data['is_show_add'] = true;

            if($start_time && $end_time){

                $data['sum_amount'] = $sum_amount ?? 0;

            }

            return $data;

        } catch (\Exception $e) {

            $this->error = $e->getMessage();

            return [];

        }

    }



    /**

     * 订单主要详情

     * @param array $request

     * @return array

     * @author SL

     * @create 2021-06-02

     */

    public function getDataDetail($request)

    {

        try {

            $id = $request['order_id'] ?? 0;

            if(!$id){

                $this->error = '请传入订单id';

                return [];

            }

            $detail = [];

            $field = ['id,order_no,consignee,operator_name,sale_name,shop_name,business_type,order_type,income_type,status,is_pay,total_amount,discount_amount,

            pay_amount,gift_amount,order_amount,shop_transfer_amount,coupon_id,coupon_name,is_experience,is_outreach,outreahc_name,is_introduction,introduction_name,

            deal_time,create_time,king_push_time,king_status,shop_market','coupon_id','coupon_name','sales_name','settlement_name','market_name','pay_time','king_sale_no','delivery_name',

                'experience_id,outreahc_id,introduction_id,project_type,business_two_type,description'
            ];

            $detail = $this->where('id',$id)->field($field)->find();

            if($detail){
                $business_two_type = [
                    1=>'身体项目',
                    2=>'皮肤项目',
                ];
                $detail['business_two_type_text'] =  $business_two_type[$detail['business_two_type']]??'暂无';

                $project_type = [
                    1=>'手术',
                    2=>'注射',
                    3=>'光电',
                    4=>'生美皮肤',
                    5=>'身体'
                ];
                $detail['project_type_name'] = isset($project_type[$detail['project_type']])?$project_type[$detail['project_type']]:'暂无';


                // 时间转化

                $detail['pay_time'] = $detail['pay_time'] ? date('Y-m-d H:i:s', $detail['pay_time']) : '';

                $detail['king_push_time'] = $detail['king_push_time'] ? date('Y-m-d H:i:s', $detail['king_push_time']) : '';

                $detail['complete_time'] = $detail['complete_time'] ? date('Y-m-d H:i:s', $detail['complete_time']) : '';

                $detail['cancel_time'] = $detail['cancel_time'] ? date('Y-m-d H:i:s', $detail['cancel_time']) : '';

                $businessType = Db::name('customer_balance_category')->column('name','id');
                $detail['business_type']    = isset($businessType[$detail['business_type']])?$businessType[$detail['business_type']]:'';

                $type_store = [
                    1=>'初诊',2=>'复诊',3=>'再消费',4=>'诊疗',5=>'其他'
                ];

                $detail['order_type']    = $type_store[$detail['order_type']]??'';

                $detail['deal_time'] = $detail['deal_time'] ? date('Y-m-d', $detail['deal_time']) : '';

                switch ($detail['status']) {
                    case '1':
                        $detail['status_msg'] = '已支付';
                        break;
                    case '2':
                        $detail['status_msg'] = '已下推';
                        break;
                    case '3':
                        $detail['status_msg'] = '已评价';
                        break;
                    case '4':
                        $detail['status_msg'] = '已作废';
                        break;
                    default:
                        $detail['status_msg'] = '待支付';
                        break;
                }

            }

            else{

                $this->error = '订单不存在';

                return false;

            }

            $userId  = $request['user_id'] ?? 0;

            $permission = get_user_permission_menu($userId,'order_list_tag');

            $detail['menu_list'] = $permission ? $permission : [];

            return $detail;

        } catch (\Exception $e) {

            $this->error = $e->getMessage();

            return [];

        }

    }


	/*
	* 修改订单--销售出库单
	* @create 2022-04-19

	*/

    public function updateDataDetail($request)
    {
        try{
            $order = $this->find($request['id']);
            if(empty($order)){
                throw new \Exception('订单不存在');
            }
            if($order->status ==3 ){
                throw new \Exception('该订单已经作废，无法修改');
            }
            $order->order_type=$request['order_type'];
            if(!empty($request['goodsList'])){
                $shopOrderGoodsModel = new ShopOrderGoods();
                $serviceModel = new Service();
                $goodsList = $request['goodsList'];
                foreach($goodsList as $k =>$v){
                    $update =[];
                    $update['goods_alias_name'] = isset($v['goods_alias_name'])?$v['goods_alias_name']:'';
                    $update['update_time'] = time();
                    $shopOrderGoodsModel->where('id',$v['id'])->update($update);
                    if($v['is_project'] == 1){
                        $service = $serviceModel->where('customer_id',$order->uid)->where('order_goods_id',$v['id'])->find();
                        $service->goods_alias_name =  $update['goods_alias_name'];
                        $service->update_time = $update['update_time'];
                        $service->save();
                    }
                }
            }

            $res=$order->save();
            if($res) {
                return ['msg'=>"更新完毕",'code'=>200];
            }else{
                throw new \Exception('更新失败');
            }
        } catch (\Exception $e) {
            $this->error = $e->getMessage();
            return [];

        }

    }


    /**

     * 订单商品详情

     * @param array $request

     * @return array

     * @author SL

     * @create 2021-06-02

     */

    public function getGoodsDataDetail($request)
    {

        try {
            $id = $request['order_id'] ?? 0;
            if(!$id){
                throw new \Exception('请传入订单id');
            }

            $detail = ShopOrderModel::find($id);
            if(empty($detail)) {
                throw new \Exception('订单不存在');
            }
            // 订单商品

            $list = ShopOrderGoods::where('order_id', $id)
                ->field('id,goods_alias_name,takeout_stock_num,number,pay_price,goods_price,goods_name,project_type,is_project,service_goods_str,project_type,prestock_type,service_number,start_time,end_time')
                ->order('id','desc')
                ->select()->toArray();

            $prestock_type = [
                1=>'不存货', 2=>'存货', 3=>'出货',
            ];
            $is_project = [
                0=>"----",1=>'品项', 2=>'商品',
            ];
            $service_type  = [
                0=>"----",1=>'按次',2=>"疗程"
            ];

            foreach ($list as $key => &$val) {
                $val['project_type_text'] = $service_type[$val['project_type']]??'';
                $val['is_project_text'] = $is_project[$val['is_project']]??'';
                $val['order_goods_price'] = bcmul($val['pay_price'],$val['number'],2);
                $val['prestock_type'] = $prestock_type[$val['prestock_type']]??'';

                $val['project_time_num']  = '----';
                if($val['is_project'] == 1 && $val['project_type'] == 1){
                    $val['project_time_num'] = $val['service_number'].'次';
                } elseif($val['is_project'] == 1 && $val['project_type'] == 2){
                    $val['project_time_num'] = date('Y-m-d h:i',$val['start_time']).'-'.date('Y-m-d h:i',$val['end_time']);
                }
                $val['children'] = [];
                if(!empty($val['service_goods_str'])){
                   $children = json_decode($val['service_goods_str'],1);
                   $childrens = [];
                   foreach ($children as $k=>$v){
                       $child=[];
                       $child['id'] =$v['id'];
                       $child['goods_name'] =$v['name'];
                       $child['goods_alias_name'] = '----';
                       $child['is_project_text'] = '商品';
                       $child['goods_price'] =$v['goods_price'];
                       $child['pay_price'] = '----';
                       $child['number'] = $v['number'];
                       $child['order_goods_price'] = '----';
                       $child['project_type_text'] = '----';
                       $child['project_time_num'] = '----';
                       $child['prestock_type'] = '----';
                       $child['takeout_stock_num'] = '----';
                       $child['service_goods_str'] = '----';
                       $child['start_time'] = '----';
                       $child['end_time'] = '----';
                       $child['project_type'] = '----';
                       $child['is_project'] = '----';
                       $child['service_number'] = '----';

                       array_push($childrens,$child);
                   }
                   $val['children'] = $childrens;
                }
            }
            return $list;
        } catch (\Exception $e) {
            $this->error = $e->getMessage();
            return [];
        }

    }


    /**

     * 订单商品详情

     * @param array $request

     * @return array

     * @author SL

     * @create 2021-06-02

     */

    public function orderGoodsOptionDetail($request)

    {

        try {

            $id = $request['order_id'] ?? 0;
            if(!$id){
                $this->error = '请传入订单id';
                return [];
            }

            $list =[];
            $detail = Db::name('shop_order')->field('id')->where('id',$id)->find();

            if($detail)
            {
                $list = ShopOrderGoodsOptionLog::with(['NurseOne'=>function($query){
                    $query->field('name,id');
                },'NurseTwo'=>function($query){
                    $query->field('name,id');
                },'shopGoods'=>function($query){
                    $query->field('id,goods_name');
                }]) ->field('id,nurse_one,nurse_two,nurse_one_project,nurse_two_project,create_time,shop_order_goods_id,is_new')
                    ->where('order_id', $id)
                    ->order('id DESC')
                    ->select()->toArray();

                foreach ($list as $key => &$value)
                {
                    $value['nurse_one_name'] = !empty($value['NurseOne'])?$value['NurseOne']['name']:'';
                    $value['nurse_one'] = !empty($value['NurseOne'])?$value['NurseOne']['id']:'';
                    $value['nurse_two_name'] = !empty($value['NurseTwo'])?$value['NurseTwo']['name']:'';
                    $value['nurse_two'] = !empty($value['NurseTwo'])?$value['NurseTwo']['id']:'';
                    $value['goods_name'] = !empty($value['shopGoods'])?$value['shopGoods']['goods_name']:'';
                    $value['nurse_one_project_text'] = $value['nurse_two_project_text'] = '';

                    if(!empty($value['nurse_one_project'])){
                        $one_project = explode(',',$value['nurse_one_project']);
                        $project_data = Db::name('shop_person_controls')->whereIn('id',$one_project)->field('id as value,name as lable')->select()->toArray();
                        $value['nurse_one_project'] = array_column($project_data,'value');
                        $value['nurse_one_project_text'] = implode(',',array_column($project_data,'lable'));
                    }
                    if(!empty($value['nurse_two_project'])){
                        $two_project = explode(',',$value['nurse_two_project']);
                        $project_data = Db::name('shop_person_controls')->whereIn('id',$two_project)->field('id as value,name as lable')->select()->toArray();
                        $value['nurse_two_project'] = array_column($project_data,'value');
                        $value['nurse_two_project_text'] = implode(',',array_column($project_data,'lable'));
                    }
                }
            } else{
                $this->error = '订单不存在';
                return false;
            }

            $detail['list'] = $list;

            return $detail;

        } catch (\Exception $e) {

            $this->error = $e->getMessage();

            return [];
        }

    }

    /**

     * 订单验证公共方法

     * @param  array $data 请求参数

     * @return bool

     * @author SL

     * @create 2021-06-03

     */

    function orderAdd($data){

        $result=['status'=>1,'error'=>''];

        if (isset($data['is_outreach'])) {
            if (!isset($data['outreahc_id'])) {
                $result['error']='外联选是时，外联人必须选择';
                $result['status']=0;
                return $result;
            }
        }

        if (isset($data['is_introduction'])) {
            if (!isset($data['introduction_id'])) {
                $result['error']='转介绍选是时，转介绍人必须选择';
                $result['status']=0;
                return $result;
            }
        }
        return $result;
    }

    /**
     * 创建订单
     * @param  array $request 请求参数
     * @return bool
     * @author SL
     * @create 2021-06-03
     */

    public function addData($request)
    {

        try {
            $validate = new \app\shop\validate\Order();
            if (!$validate->scene('create')->check($request)) {
                $this->error = $validate->getError();
                return false;
            }
        }catch (\Exception $e) {
            $this->error = $e->getMessage();
            return false;
        }
        //检查订单是否已经录入
        if(!empty($request['api_order_id']))
        {
            $check_count = Db::name('shop_order')->where('api_order_id',$request['api_order_id'])->count();
            if($check_count > 0)
            {
                $this->error = '此商城订单已经录入';
                return false;
            }
        }

        Db::startTrans();
        try {

            $deal_time = strtotime($request['deal_time']);
            $refundModel = new Refund();
            $orderVerfiy = $refundModel->orderVerfiy(5,$deal_time);
            if(!$orderVerfiy){
                throw new \Exception("订单不可创建");
            }
            $customer_id = trim($request['uid']);

            $customer_data = Customer::with(['info'=>function($query)use($customer_id){
                    $query->field('id,type_store');
            }])->where('id',$customer_id)
                ->field('source_id,source_type_id,shop_id,telephone,id')
                ->find()->toArray();
            //顾客到点类型-诊疗，无法创建订单
            if($customer_data['info']['type_store'] == 4){
                throw new \Exception("当前无法创建订单");
            }

            //验证顾客创建订单
            list($benj,$zengj,$customerMoney) = $refundModel->customerBalanceVerify($customer_id);

            $time = time();

            $orderGoodsListArr = $request['goodsList'];

            $goods_ids = array_column($orderGoodsListArr, 'id');

            $field = 'id, kingdee_code,month_allowed_entry_max,halfmonth_allowed_entry_max,is_prestock';

            $goodsInfo = ShopGoods::whereIn('id',$goods_ids)->field($field)->select()->toArray();

            $goodsInfo = array_column($goodsInfo, null, 'id');

            $shop = ShopModel::where('shop_id',$request['shop_id'])->lock(true)->field('shop_id,type,keycode,shop_name,market_name,market_id')->find();//判断直营 加盟


            // 支付总金额 /  产品的总金额 / 项目总金额，排除优惠券
            $payAmount = $productAmount = $projectAmount =   [];
            $goods_price = [];
            $order_experience =0;  //是否体验
            $is_have_cjyh = $is_have_goods =   [];
            $cjyh = 0; //自己选择冲减优惠
            $yhq_amount = 0; //优惠券优惠金额
            $yhq_name = '';
            $yhq_id = 0;
            $project_arr = $project_ids = $product_arr = $product_ids = $cjyh_arr = [];
            $kcbj = $kczj = $cjyh_bj =  $cjyh_zj = [];
            $product_project_arr = [];
            $zero_goods_arr = [];
            $prestock_goods_ids =[];
            $is_send_yxk = [];//是否推送云星空
            foreach ($orderGoodsListArr as $key => $val) {
                if($val['prestock_type'] != 3){

                    if($val['pay_price'] == 0){
                        array_push($zero_goods_arr,$val);
                    }
//                    //不存货/存货
//                    if(!in_array($val['business_type'],[1,2,3])){
//                        throw new \Exception($val['category_name'].'-请选择项目分类');
//                    }

                    if(!isset($val['number']) || empty($val['number'])  ) {
                        throw new \Exception("请填写销售数量");
                    }

                    if($val['goods_type'] == 2 && $val['prestock_type'] != 3){
                        array_push($product_ids,$val['id']);

                        if($val['id'] != 170 && $val['pay_price'] != 0){
                            if($val['pay_price'] <0){
                                throw new \Exception($val['name'].'-售卖价格错误');
                            }
                            array_push($product_project_arr,$val);
                            $productAmount[] = bcmul($val['pay_price'], $val['number'], 2);
                        }
                        array_push($is_have_goods,1);

                    }elseif($val['goods_type'] ==1 && $val['prestock_type'] != 3  && $val['pay_price'] != 0 ){
                        $projectAmount[] = bcmul($val['pay_price'], $val['number'], 2);
                        array_push($is_have_goods,1);
                        array_push($product_project_arr,$val);
                        array_push($project_ids,$val['id']);
                    }

                    if($val['id'] == 170 ){
                        if($val['pay_price'] <0){
                            throw new \Exception('冲减优惠不能为0');
                        }
                        $cjyh = bcmul($val['pay_price'], $val['number'], 2);
                        array_push($is_have_cjyh,1);
                        array_push($cjyh_arr,$val);
                        array_push($product_ids,$val['id']);
                    }


                    if($val['prestock_type'] == 2){
                        array_push($prestock_goods_ids,$val['id']);
                        array_push($is_send_yxk,0);

                    }elseif($val['goods_type'] ==1){
                        array_push($project_ids,$val['id']);
                        array_push($is_send_yxk,0);
                    }elseif($val['prestock_type'] == 1 && $val['id'] != 170 ){
                        array_push($is_send_yxk,1);
                    }

                }

                if(!isset($val['house_code']) || empty($val['house_code'])) {
                    throw new \Exception("请选择仓库");
                }


            }


            if(!empty($prestock_goods_ids)){
                //排查如果有预存货不能添加
                //针对预存货商品，进行判定
                $may_prestock_ids = ShopGoods::where('is_prestock',1)->column('id'); //可以预存货的id
                $prestock_diff = array_diff($prestock_goods_ids,$may_prestock_ids);
                if(!empty($prestock_diff)){
                    throw new \Exception('有异常预存货商品');
                }
            }

            $is_have_cjyh_count = count($is_have_cjyh);
            if($is_have_cjyh_count >1){
                throw new \Exception('同一个单子不能出现两项冲减优惠');
            }else if ($is_have_cjyh_count >0 && empty($is_have_goods)){
                throw new \Exception('冲减优惠没有优惠商品');
            } else if($is_have_cjyh_count >0 && $cjyh == 0){
                throw new \Exception('冲减优惠不能等于零');
            }


            $goods_price = bcadd(array_sum($goods_price),0,2); //商品标准价格之和
            $productAmount = bcadd(0,array_sum($productAmount),2); //商品之和
            $projectAmount = bcadd(0,array_sum($projectAmount),2); //项目之和

            $total_amount = $productProjectAmount = bcadd($productAmount,$projectAmount,2); //优惠前的订单金额

            if($is_have_cjyh_count >0 && $total_amount < $cjyh){
                throw new \Exception('冲减优惠无法使用');
            }

            $operator_name = $request['operator_name'];//操作人姓名
            $operator_id = $request['operator_id'];//操作人id



            // 验证
            $data = [
                'uid'                =>  $customer_id, // 客户
                'uid_source_type_id' =>  $customer_data['source_type_id'],
                'uid_source_id'      =>  $customer_data['source_id'],
                'consignee'          => trim($request['consignee']), // 收货人
                'order_no'           => $this->getOrderNo(), // 订单号
                'sale_id'            => $request['sale_id'], // 销售员id
                'sale_name'          => trim($request['sale_name']), // 销售员姓名
                'shop_id'            => $customer_data['shop_id'], // 门店id
                'shop_name'          => trim($shop['shop_name']), // 门店名称
                'operator_id'        => $operator_id,//制单员id
                'operator_name'      => $operator_name,//制单员姓名
                'create_time'       => $time, // 创建时间
                'deal_time'         => strtotime($request['deal_time']), // 成交日期
                'goods_price'      => $goods_price, // 订单标准金额 之和
                'total_amount'      => $total_amount, // 订单总金额 之和
                'discount_amount'   => abs($yhq_amount), // 订单优惠金额：优惠券优惠金额
                'coupon_id'         => $yhq_id, // 优惠券id
                'coupon_name'       => $yhq_name, // 优惠券名字
                'order_amount'      =>  0, // 订单优惠后的金额
                'pay_amount'        => 0, // 实收本金
                'gift_amount'        =>  0, // 实收赠金
                'shop_transfer_amount' => 0, //实收店转
                'description'           => isset($request['description']) ? $request['description'] : '', // 订单描述
                'order_type'            => $customer_data['info']['type_store'], // 订单类型 1新单 2补单-改为顾客到店类型
                'project_type'          => 0, // 项目分类
                'business_type'         => 0, // 业务类型 1项目 2疤痕 3青春痘 4护肤品
                'business_two_type'     => 0,// 业务类型二级分类  1身体项目  2 皮肤项目
                'income_type'                => $request['income_type'], // 收入类型 1 服务（各类疗程卡项及疗程卡项赠送产品）2 产品销售（单独付费购买产品）3 医美收入
                'sales_policy'               => isset($request['sales_policy'])? $request['sales_policy'] : '', // 销售政策编码
                'market_id'            => $shop['market_id'] , // 市场id
                'market_name'          => $shop['market_name'], // 市场名称
                'sales_organization'       => isset($request['sales_organization']) ? $request['sales_organization'] : 0, // 销售组织编码
                'sales_name'       => isset($request['sales_name']) ? $request['sales_name'] : '', // 销售组织名称
                'settlement_organization'       => isset($request['settlement_organization']) ? $request['settlement_organization'] : 0, // 结算组织编码
                'settlement_name'       => isset($request['settlement_name']) ? $request['settlement_name'] : '', // 结算组织名称
                'order_experience'       => $order_experience ,//订单是否有体验商品
                'delivery_name'       => isset($request['delivery_name']) ? $request['delivery_name'] : '', // 发货部门名称
                'delivery_king'       => isset($request['delivery_king']) ? $request['delivery_king'] : '', // 发货部门编码
                'api_type' => $request['api_type'] ?? 0, //0中台系统 1商城积分兑换订单 2商城普通订单
                'api_order_id' => $request['api_order_id'] ?? '', //商城订单ID
            ];
            $order = $this->create($data);

            if ($order) {
                $customerModel = new \app\crm\model\Customer();
                //产品入库
                $deduct_balance = $deduct_gift = []; //实际扣款本金、实际扣款赠金
                //商品
                $shopGoods = [];
                if(!empty($product_ids)){
                    $shopGoods = ShopGoods::whereIn('id', $product_ids)
                        ->where('status', 1)
                        ->column('name,category_id,kingdee_code,goods_price,spec_name,unit_code,unit_name,is_prestock', 'id');
                }
                //项目
                $project = [];
                if(!empty($project_ids)){
                    $project = ProductItem::whereIn('id',$project_ids)
                        ->where('status',1)
                        ->column('kingdee_code,price,name,number,product_info,type_one,type_two,type_three,unit_code,unit_name','id');
                }

                $ShopOrderGoodsModel = new ShopOrderGoods();
                $perstockGoodsList = []; //预存货

                $discount_amount_arr = [];//冲减优惠-商品优惠后的总金额
                $product_yh_amount = $product_one_amount = [];
                $product_project_arr_count = count($product_project_arr);
                $serviceDataAll =[]; //卡项添加列表
                foreach ($product_project_arr as $pk => &$pv) {

                    if ($pv['pay_price'] > 0 && $pv['prestock_type'] != 3 ) {
                        $customerBalance['money'] = $benj;
                        $customerBalance['complimentary_money'] = $zengj;

                        $one_product_amount = bcmul($pv['pay_price'], $pv['number'], 2);

                        $discount_amount = 0; //优惠金额

                        if ($productProjectAmount > 0 && $cjyh != 0) {
                            //涉及到冲减优惠
                            if ($product_project_arr_count > 1) {
                                if ($pk + 1 == $product_project_arr_count) {
                                    $discount_amount = bcsub($cjyh, bcadd(0, array_sum($discount_amount_arr), 2), 2); //最后一个优惠金额
                                } else {
                                    $discount_amount = bcmul($cjyh, ($one_product_amount/$productProjectAmount), 2); //优惠金额
                                }
                            } else {
                                $discount_amount = bcmul($cjyh, ($one_product_amount/$productProjectAmount), 2); //优惠金额
                            }

                            $one_product_amount = bcadd($one_product_amount, $discount_amount, 2);
                        }
                        array_push($discount_amount_arr, $discount_amount);


                        $customerBalance['actual_order_amout'] = $one_product_amount;
                        $pay_money = $customerModel->getCustomerAmountConsumed($customerBalance); //获取订单消耗的本金、赠金、店转
                        $bj = bcadd($pay_money['pay_benjin_amount'], 0, 2);  //单条优惠后的本金
                        $zj = bcadd($pay_money['pay_zengjin_amount'], 0, 2); //单条优惠后的赠金



                        array_push($kcbj, $bj);
                        array_push($kczj, $zj);

                        $customerBalance['actual_order_amout'] = $discount_amount;

                        $cjyh_pay_money = $customerModel->getCustomerAmountConsumed($customerBalance); //获取订单消耗的本金、赠金、店转
                        $pv['discount_amount'] = $discount_amount;    //折扣金额

                        $cjyhbj = bcadd($cjyh_pay_money['pay_benjin_amount'], 0, 2);  //单条优惠后的本金
                        $cjyhzj = bcadd($cjyh_pay_money['pay_zengjin_amount'], 0, 2); //单条优惠后的赠金
                        array_push($cjyh_bj, $cjyhbj);
                        array_push($cjyh_zj, $cjyhzj);

                        $pv['after_discount_amount'] = $one_product_amount;    //优惠后金额
                        array_push($product_yh_amount, $discount_amount);
                        array_push($product_one_amount, $one_product_amount);
                    }


                    $orderGoodsList = [];
                    $orderGoodsList['pay_amount'] = $bj;
                    $orderGoodsList['gift_amount'] = $zj;
                    $orderGoodsList['shop_transfer_amount'] = 0;
                    $orderGoodsList['order_id'] = $order->id;
                    $orderGoodsList['create_time'] = $time;
                    $orderGoodsList['goods_id'] = $pv['id'];


                    if($pv['goods_type'] == 1){
                        $orderGoodsList['goods_name'] = $pv['name'];
                        $orderGoodsList['kingdee_code'] = isset($project[$pv['id']])?$project[$pv['id']]['kingdee_code']:'';
                        $orderGoodsList['goods_price']  =  $pv['goods_price'];
                        $orderGoodsList['pay_price']    = $pv['pay_price'];
                        $orderGoodsList['spec_name'] = $pv['spec_name'];

                        $orderGoodsList['unit_code'] = isset($project[$pv['id']])?$project[$pv['id']]['unit_code']:'';
                        $orderGoodsList['unit_name'] =  isset($project[$pv['id']])?$project[$pv['id']]['unit_name']:'';

                        $orderGoodsList['number'] = $pv['number'];
                        $orderGoodsList['desc'] = $pv['desc'];
                        $orderGoodsList['is_project'] = 1;//是否服务 1 是 2否
                        $orderGoodsList['category_id'] =  $jv['category_id']??0;
                        $orderGoodsList['service_goods_str'] = isset($project[$pv['id']])?$project[$pv['id']]['product_info']:'';
                        $orderGoodsList['is_coupon_goods'] =  0;;//是否优惠券商品 0否 1是
                        $orderGoodsList['project_type'] =  1;//服务类型 1 按次 2按天
                        $orderGoodsList['service_number'] = isset($project[$pv['id']])?$project[$pv['id']]['number']:0;//服务次数
                    }
                    else if($pv['goods_type'] == 2){
                        $orderGoodsList['goods_name'] = $shopGoods[$pv['id']]['name'];
                        $orderGoodsList['kingdee_code'] = $shopGoods[$pv['id']]['kingdee_code'];
                        $orderGoodsList['goods_price'] = $shopGoods[$pv['id']]['goods_price'];
                        $orderGoodsList['pay_price'] = $pv['pay_price'];
                        $orderGoodsList['spec_name'] = $shopGoods[$pv['id']]['spec_name'];
                        $orderGoodsList['unit_code'] = $shopGoods[$pv['id']]['unit_code'];
                        $orderGoodsList['unit_name'] = $shopGoods[$pv['id']]['unit_name'];
                        $orderGoodsList['number'] = $pv['number'];
                        $orderGoodsList['desc'] = $pv['desc'];
                        $orderGoodsList['is_project'] = 2;//是否服务 1 是 2否
                        $orderGoodsList['category_id'] = $shopGoods[$pv['id']]['category_id'];

                    }

                    $orderGoodsList['is_gift'] = isset($pv['is_gift']) ? $pv['is_gift'] : 0;  //是否为赠品
                    $orderGoodsList['house_code'] = $pv['house_code'];
                    $orderGoodsList['coupon_type'] = isset($pv['coupon_type']) ? $pv['coupon_type'] : 0;//优惠券类型
                    $orderGoodsList['house_code_name'] = isset($pv['house_code_name']) ? $pv['house_code_name'] : '';
                    $orderGoodsList['goods_alias_name'] = isset($pv['goods_alias_name']) ? $pv['goods_alias_name'] : '';
                    $orderGoodsList['prestock_type'] = isset($pv['prestock_type']) ? $pv['prestock_type'] : 0; //预存货类型
                    $orderGoodsList['takeout_stock_num'] = isset($pv['out_num']) ? $pv['out_num'] : 0;  //出货数量
                    $orderGoodsList['data_business_type'] = isset($pv['business_type']) ? $pv['business_type'] : 0;  //业务类型
                    $orderGoodsList['data_business_two_type'] = isset($pv['business_two_type']) ? $pv['business_two_type'] : 0;  //业务类型
                    $orderGoodsList['discount_amount'] = isset($pv['discount_amount']) ? $pv['discount_amount'] : 0;  ////折扣金额

                    $orderGoodsList['after_discount_amount'] = isset($pv['after_discount_amount']) ? $pv['after_discount_amount'] : 0;  //优惠后金额

                    $order_goods_res = $ShopOrderGoodsModel->create($orderGoodsList);
                    //需要预存的货
                    if ($pv['prestock_type'] == 2 && $pv['goods_type'] == 2) {
                        $perstockGoods = [];
                        $perstockGoods['operator_id'] = $operator_id;
                        $perstockGoods['business_type'] = $orderGoodsList['data_business_type'];  //业务类型
                        $perstockGoods['business_two_type'] = $orderGoodsList['data_business_two_type'];  //业务类型
                        $perstockGoods['shop_id'] = $shop['shop_id'];
                        $perstockGoods['customer_id'] = $customer_id;
                        $perstockGoods['deal_time'] = $data['deal_time'];
                        $perstockGoods['goods_price'] = $orderGoodsList['pay_price'];
                        $perstockGoods['goods_id'] = $pv['id'];
                        $perstockGoods['order_id'] = $order->id;
                        $perstockGoods['order_goods_id'] = $order_goods_res->id;
                        $perstockGoods['create_time'] = $time;
                        $perstockGoods['update_time'] = $time;
                        $perstockGoods['is_use'] = 0;
                        $perstockGoods['num'] = $orderGoodsList['takeout_stock_num'];
                        $perstockGoods['service_type'] = $orderGoodsList['project_type'];
                        $perstockGoods['service_num'] = $orderGoodsList['service_number'];
                        $perstockGoods['project_begin_time'] = $orderGoodsList['start_time'];
                        $perstockGoods['project_end_time'] = $orderGoodsList['end_time'];
                        $perstockGoods['goods_type'] = $orderGoodsList['is_project'];

                        array_push($perstockGoodsList, $perstockGoods);
                    }

                    //卡项添加
                    if($pv['goods_type'] == 1){
                        list($once_cancel_balance,$once_cancel_gift,$last_cancel_balance,$last_cancel_gift,$once_discount_amount,$last_discount_amount) = $this->getRealCancelAmount($orderGoodsList);
                        //服务卡项
                        //品项添加-按照次卡形式
                        for($i=1;$i<=$orderGoodsList['number'];$i++){
                            $oneService = [];
                            $oneService['name']    = $orderGoodsList['goods_name'];  //服务名称
                            $oneService['goods_alias_name']    = $orderGoodsList['goods_alias_name'];  //服务名称
                            $oneService['shop_id'] =  $data['shop_id'];    // 店铺id
                            $oneService['customer_id']  = $data['uid'];   // 必填--客户id
                            $oneService['order_id']  = $order->id;
                            $oneService['order_goods_id']  = $order_goods_res->id;
                            $oneService['service_type'] = 2;   // 必填--服务类型：1按期2按次
                            $oneService['num'] = isset($project[$pv['id']])?$project[$pv['id']]['number']:0;   // 次卡可服务次数
                            $oneService['start_time']   = 0;    // 类型为1 是必填--服务开始时间
                            $oneService['end_time']     = 0;      // 类型为1 是必填--服务开始时间
                            $oneService['experience']   = 0;     // 0否1是 是否体验
                            $oneService['kk_user_id']   = $data['sale_id'];     // 开卡人id
                            $oneService['goods_id']     = $orderGoodsList['goods_id'];
                            $kk_money = bcmul($pv['pay_price'],1,2);

                            if($kk_money>0){
                                $customerBalance['actual_order_amout'] = $kk_money;
                                $balance_consumed = $customerModel->getCustomerAmountConsumed($customerBalance);
                                $oneService['consume_store_transfer'] = 0;
                                $oneService['consume_gratuity'] =  $balance_consumed['pay_zengjin_amount'];
                                $oneService['consume_money'] =  $balance_consumed['pay_benjin_amount'];
                            }

                            if($i == 1){
                                $oneService['real_cancel_balance'] = $once_cancel_balance;
                                $oneService['real_cancel_gift'] = $once_cancel_gift;
                                $oneService['discount_amount'] = $once_discount_amount;
                            }
                            else{
                                if($i<$orderGoodsList['number'] ){
                                    $oneService['real_cancel_balance'] = $once_cancel_balance;
                                    $oneService['real_cancel_gift'] =  $once_cancel_gift;
                                    $oneService['discount_amount'] = $once_discount_amount;
                                }
                                elseif($i==$orderGoodsList['number'] ){
                                    $oneService['real_cancel_balance'] = $last_cancel_balance;
                                    $oneService['real_cancel_gift'] =  $last_cancel_gift;
                                    $oneService['discount_amount'] = $last_discount_amount;
                                }
                            }

                            $oneService['service_max_num'] = $oneService['num']; //最高进店次数
                            $oneService['kk_money']     = $kk_money;       // 开卡金额
                            $oneService['category_type_one']  = isset($project[$pv['id']])?$project[$pv['id']]['type_one']:0;       // 品项的一级分类
                            $oneService['category_type_two']  = isset($project[$pv['id']])?$project[$pv['id']]['type_two']:0;       // 开卡金额
                            $oneService['category_type_three']  = isset($project[$pv['id']])?$project[$pv['id']]['type_three']:0;       // 开卡金额
                            array_push($serviceDataAll,$oneService);
                        }
                    }

                }

                //添加顾客预存货列表
                if (!empty($perstockGoodsList)) {
                    $customerPrestockGoodsModel = new  CustomerPrestockGoods();
                    $customerPrestockGoodsModel->saveAll($perstockGoodsList);
                }

                //添加服务卡项
                if(!empty($serviceDataAll)){
                    $addServiceRes = $customerModel->addCustomService($customer_id,$serviceDataAll);
                    if(!$addServiceRes){
                        throw new \Exception("服务创建失败");
                    }
                }


                //冲减优惠入库
                foreach ($cjyh_arr as $ck => &$cv) {
                    $orderGoodsList = [];
                    $orderGoodsList['pay_amount'] = bcadd(0,array_sum($cjyh_bj),2);
                    $orderGoodsList['gift_amount'] =  bcadd(0,array_sum($cjyh_zj),2);
                    $orderGoodsList['shop_transfer_amount'] = 0;
                    $orderGoodsList['order_id'] = $order->id;
                    $orderGoodsList['create_time'] = $time;
                    $orderGoodsList['goods_id'] = $cv['id'];
                    $orderGoodsList['goods_name'] = $shopGoods[$cv['id']]['name'];
                    $orderGoodsList['kingdee_code'] = $shopGoods[$cv['id']]['kingdee_code'];
                    $orderGoodsList['goods_price'] = $shopGoods[$cv['id']]['goods_price'];
                    $orderGoodsList['pay_price'] = $cv['pay_price'];
                    $orderGoodsList['spec_name'] = $shopGoods[$cv['id']]['spec_name'];
                    $orderGoodsList['unit_code'] = $shopGoods[$cv['id']]['unit_code'];
                    $orderGoodsList['unit_name'] = $shopGoods[$cv['id']]['unit_name'];
                    $orderGoodsList['number'] = $cv['number'];
                    $orderGoodsList['desc'] = $cv['desc'];
                    $orderGoodsList['is_project'] = 2;//是否服务 1 是 2否
                    $orderGoodsList['category_id'] = $shopGoods[$cv['id']]['category_id'];
                    $orderGoodsList['is_coupon_goods'] = 0;//是否优惠券商品 0否 1是
                    $orderGoodsList['project_type'] = 0;//服务类型 1 按次 2按天
                    $orderGoodsList['service_number'] = 0;//服务次数
                    $orderGoodsList['start_time'] = 0; //服务开始时间
                    $orderGoodsList['end_time'] = 0;  //服务结束时间
                    $orderGoodsList['is_gift'] = isset($cv['is_gift']) ? $cv['is_gift'] : 0;  //是否为赠品
                    $orderGoodsList['house_code'] = $cv['house_code'];
                    $orderGoodsList['coupon_type'] = isset($cv['coupon_type']) ? $cv['coupon_type'] : 0;//优惠券类型
                    $orderGoodsList['house_code_name'] = isset($cv['house_code_name']) ? $cv['house_code_name'] : '';
                    $orderGoodsList['goods_alias_name'] = isset($cv['goods_alias_name']) ? $cv['goods_alias_name'] : '';
                    $orderGoodsList['prestock_type'] = isset($cv['prestock_type']) ? $cv['prestock_type'] : 0; //预存货类型
                    $orderGoodsList['takeout_stock_num'] = isset($cv['out_num']) ? $cv['out_num'] : 0;  //出货数量
                    $orderGoodsList['data_business_type'] = isset($cv['business_type']) ? $cv['business_type'] : 0;  //业务类型
                    $orderGoodsList['data_business_two_type'] = isset($cv['business_two_type']) ? $cv['business_two_type'] : 0;  //业务类型
                    $orderGoodsList['after_discount_amount'] =  bcmul($cv['pay_price'],$cv['number'],2);
                    $order_goods_res = $ShopOrderGoodsModel->create($orderGoodsList);
                }
                $zeroperstockGoodsList = [];//0元预存货
                $zeroserviceDataAll = [];//0元卡项
                //0元单 商品+品相
                foreach ($zero_goods_arr as $zk => &$zv) {
                    $orderGoodsList = [];
                    $orderGoodsList['pay_amount'] =0;
                    $orderGoodsList['gift_amount'] =  0;
                    $orderGoodsList['shop_transfer_amount'] = 0;
                    $orderGoodsList['order_id'] = $order->id;
                    $orderGoodsList['create_time'] = $time;
                    $orderGoodsList['goods_id'] = $zv['id'];
                    $orderGoodsList['is_project'] = $zv['goods_type'];//是否服务 1 是 2否
                    if($zv['goods_type'] ==1){
                        //品项
                        $orderGoodsList['goods_name'] = $project[$zv['id']]['name']??'';
                        $orderGoodsList['kingdee_code'] = $project[$zv['id']]['kingdee_code']??'';
                        $orderGoodsList['goods_price'] = $project[$zv['id']]['goods_price']??'';
                        $orderGoodsList['pay_price'] = $zv['pay_price'];
                        $orderGoodsList['spec_name'] = $project[$zv['id']]['spec_name']??'';
                        $orderGoodsList['unit_code'] = $project[$zv['id']]['unit_code']??'';
                        $orderGoodsList['unit_name'] = $project[$zv['id']]['unit_name']??'';
                        $orderGoodsList['category_id'] = 0;
                        $orderGoodsList['service_number'] = $project[$zv['id']]['number']??0;//服务次数
                        $orderGoodsList['service_goods_str'] = isset($project[$zv['id']])?$project[$zv['id']]['product_info']:'';
                    }else{
                        //商品
                        $orderGoodsList['goods_name'] = $shopGoods[$zv['id']]['name']??'';
                        $orderGoodsList['kingdee_code'] = $shopGoods[$zv['id']]['kingdee_code']??'';
                        $orderGoodsList['goods_price'] = $shopGoods[$zv['id']]['goods_price']??'';
                        $orderGoodsList['pay_price'] = $zv['pay_price'];
                        $orderGoodsList['spec_name'] = $shopGoods[$zv['id']]['spec_name']??'';
                        $orderGoodsList['unit_code'] = $shopGoods[$zv['id']]['unit_code']??'';
                        $orderGoodsList['unit_name'] = $shopGoods[$zv['id']]['unit_name']??'';
                        $orderGoodsList['category_id'] = $shopGoods[$zv['id']]['category_id']??'';
                        $orderGoodsList['service_number'] =  0;//服务次数
                    }

                    $orderGoodsList['number'] = $zv['number'];
                    $orderGoodsList['desc'] = $zv['desc'];
                    $orderGoodsList['is_coupon_goods'] = 0;//是否优惠券商品 0否 1是
                    $orderGoodsList['start_time'] = 0; //服务开始时间
                    $orderGoodsList['end_time'] = 0;  //服务结束时间
                    $orderGoodsList['is_gift'] = isset($zv['is_gift']) ? $zv['is_gift'] : 0;  //是否为赠品
                    $orderGoodsList['house_code'] = $zv['house_code'];
                    $orderGoodsList['coupon_type'] = isset($zv['coupon_type']) ? $zv['coupon_type'] : 0;//优惠券类型
                    $orderGoodsList['house_code_name'] = isset($zv['house_code_name']) ? $zv['house_code_name'] : '';
                    $orderGoodsList['goods_alias_name'] = isset($cv['goods_alias_name']) ? $zv['goods_alias_name'] : '';
                    $orderGoodsList['prestock_type'] = isset($zv['prestock_type']) ? $zv['prestock_type'] : 0; //预存货类型
                    $orderGoodsList['takeout_stock_num'] = isset($zv['out_num']) ? $zv['out_num'] : 0;  //出货数量
                    $orderGoodsList['data_business_type'] = isset($zv['business_type']) ? $zv['business_type'] : 0;  //业务类型
                    $orderGoodsList['data_business_two_type'] = isset($zv['business_two_type']) ? $zv['business_two_type'] : 0;  //业务类型
                    $orderGoodsList['after_discount_amount'] = 0;
                    $order_goods_res = $ShopOrderGoodsModel->create($orderGoodsList);

                    if($zv['goods_type'] ==1){
                        //品项开卡-按照次卡形式
                        for($i=1;$i<=$orderGoodsList['number'];$i++){
                            $oneService = [];
                            $oneService['name']    = $orderGoodsList['goods_name'];  //服务名称
                            $oneService['goods_alias_name']    = $orderGoodsList['goods_alias_name'];  //服务名称
                            $oneService['shop_id'] =  $data['shop_id'];    // 店铺id
                            $oneService['customer_id']  = $data['uid'];   // 必填--客户id
                            $oneService['order_id']  = $order->id;
                            $oneService['order_goods_id']  = $order_goods_res->id;
                            $oneService['service_type'] = 2;   // 必填--服务类型：1按期2按次
                            $oneService['num'] = isset($project[$zv['id']])?$project[$zv['id']]['number']:0;   // 次卡可服务次数
                            $oneService['start_time']   = 0;    // 类型为1 是必填--服务开始时间
                            $oneService['end_time']     = 0;      // 类型为1 是必填--服务开始时间
                            $oneService['experience']   = 0;     // 0否1是 是否体验
                            $oneService['kk_user_id']   = $data['sale_id'];     // 开卡人id
                            $oneService['goods_id']     = $orderGoodsList['goods_id'];
                            $oneService['service_max_num'] = $oneService['num']; //最高进店次数
                            $oneService['kk_money']     = 0;       // 开卡金额
                            $oneService['category_type_one']  = isset($project[$zv['id']])?$project[$zv['id']]['type_one']:0;       // 品项的一级分类
                            $oneService['category_type_two']  = isset($project[$zv['id']])?$project[$zv['id']]['type_two']:0;       // 开卡金额
                            $oneService['category_type_three']  = isset($project[$zv['id']])?$project[$zv['id']]['type_three']:0;       // 开卡金额
                            array_push($zeroserviceDataAll,$oneService);
                        }
                    } //需要预存的货
                    if ($zv['prestock_type'] == 2 &&  $zv['goods_type'] ==1) {
                        $perstockGoods = [];
                        $perstockGoods['operator_id'] = $operator_id;
                        $perstockGoods['business_type'] = $orderGoodsList['data_business_type'];  //业务类型
                        $perstockGoods['business_two_type'] = $orderGoodsList['data_business_two_type'];  //业务类型
                        $perstockGoods['shop_id'] = $shop['shop_id'];
                        $perstockGoods['customer_id'] = $customer_id;
                        $perstockGoods['deal_time'] = $data['deal_time'];
                        $perstockGoods['goods_price'] = $orderGoodsList['pay_price'];
                        $perstockGoods['goods_id'] = $zv['id'];
                        $perstockGoods['order_id'] = $order->id;
                        $perstockGoods['order_goods_id'] = $order_goods_res->id;
                        $perstockGoods['create_time'] = $time;
                        $perstockGoods['update_time'] = $time;
                        $perstockGoods['is_use'] = 0;
                        $perstockGoods['num'] = $orderGoodsList['takeout_stock_num'];
                        $perstockGoods['service_type'] = $orderGoodsList['project_type'];
                        $perstockGoods['service_num'] = $orderGoodsList['service_number'];
                        $perstockGoods['project_begin_time'] = $orderGoodsList['start_time'];
                        $perstockGoods['project_end_time'] = $orderGoodsList['end_time'];
                        $perstockGoods['goods_type'] = $zv['is_project'];
                        $perstockGoods['remark'] = '';
                        array_push($zeroperstockGoodsList, $perstockGoods);
                    }

                }
                //0元单 卡项开卡
                if(!empty($zeroserviceDataAll)){
                    $addServiceRes = $customerModel->addCustomService($customer_id,$zeroserviceDataAll);
                    if(!$addServiceRes){
                        throw new \Exception("服务创建失败");
                    }
                }
                //0元单-预存货添加
                if (!empty($zeroperstockGoodsList)) {
                    $customerPrestockGoodsModel = new  CustomerPrestockGoods();
                    $customerPrestockGoodsModel->saveAll($zeroperstockGoodsList);
                }
                //推云星空使用
                $shop_order_update= [
                    'pay_amount'     => bcadd(array_sum($kcbj),0,2), // 实收本金
                    'gift_amount'    => bcadd(array_sum($kczj),0,2), // 实收赠金
                    'shop_transfer_amount' =>0, //实收店转
                ];
                $shop_order_update['total_amount'] = $shop_order_update['order_amount'] = bcadd($shop_order_update['pay_amount'],$shop_order_update['gift_amount'],2);
                if(!in_array(1,$is_send_yxk)){
                    $shop_order_update['status'] =2;
                }
                $res = ShopOrderModel::where('id',$order->id)->update($shop_order_update);

                //处理顾客的预存
                $balanceData   = [
                    'change_type'  => 2,      // 变动类型 1:增加 2:减少
                    'change_balance' => $shop_order_update['pay_amount'],
                    'change_gift_balance' => $shop_order_update['gift_amount'],
                ];
                // 新单变更数据集
                $newOrderData  = [  ];
                // 本次需要新增的订单金额
                $orderInfo     = [
                    'customer_id'=>$customer_id,
                    'order_id'=>$order->id,
                    'type'=>4,
                    'notes'=>707,
                    'remarks'=>'出货单'
                ];

                $yhjOrderInfo  = [    // 本次需要处理的优惠卷
                    'yhj_id'     => isset($request['yhj_id'])?$request['yhj_id']:0,      // 本次优惠卷的id
                    'order_id'  => $order->id,   // 本次订单的id
                    'order_no'  => $data['order_no'],   // 本次订单的id
                    'operator_id' => $data['sale_id'],  // 核销人的id
                ];

                $customerModel->processingFunds($customer_id,$balanceData,$request['deal_time'],$newOrderData,$orderInfo,$yhjOrderInfo);

                // 生成出库记录
                $addLogModel = new AddOrderLog();
                $deal_time = strtotime($request['deal_time']);
                $addLogModel->addData($customer_id,$request['shop_id'],$order->order_no,$deal_time,'4');
                // var_dump($is_send_yxk);die;


                // 金蝶推送云星空订单
                if(in_array(1,$is_send_yxk)){
                    $refundModel = new Refund();
                    $refundModel->sendYxk($customer_id,4,$order->id);
                }
                Db::commit();
                /******************给顾客发短信 -仅限川渝市场-start************/
                $shop_id = $request['shop_id'];
                $shopinfo = Db::name('shop')->where('shop_id',$shop_id)->field('shop_name,city_name,market_id')->find();
                $consumption_amount = bcadd((string)($balanceData['change_balance'] ?? 0), (string)($balanceData['change_gift_balance'] ?? 0), 2); //订单金额

                if($consumption_amount >0)
                {
                        $shopName = $shopinfo['shop_name'];

                        $customerData  = DB::name('customer')->where('id',$customer_id)->field('telephone,is_show_balance,customer_name')->find();
                        $is_send = $customerData['is_show_balance'];
                        $telephone = $customerData['telephone'];
                        $customer_name = $customerData['customer_name'];

                        $refundModel = new Refund();
                        $open_id = $refundModel->is_send_msgtemplate($telephone);
                        if(!empty($open_id)){
                            //推送公众号
                            $time = date('Y-m-d h:i:s',$time); //创建订单时间
                            //退货
                            $sendData = [
                                'open_id'=>$open_id,
                                'data'=>[
                                    'thing1'=>['value'=>$shopName],
                                    'time5'=>['value'=>$time],
                                    'amount3'=>['value'=>$consumption_amount],
                                    'thing12'=>['value'=>$customer_name],
                                ]
                            ];
                            $refundModel->send_msg(4,$sendData);
                        }else{
                            $residue_amount = Db::name('customer_account')->where('id', $customer_id)->value('(IFNULL(balance, 0) + IFNULL(gift, 0))'); //消费后剩余余额
                            $sendData = [
                                'market_id' => $shopinfo['market_id'],
                                'shop_id' => $request['shop_id'],
                                'customer_id' => $customer_id,
                                'telephone' => $telephone,
                                'content' => '【欣奕除疤】尊敬的客户您好，您于'.date('y-m-d H:i',$time).'分 在'.$shopName.'服务中心消费'.$consumption_amount.'元，当前余额'.$residue_amount.'元，如有疑问，可致电400-668-8162。拒收请回复R',
                                'type' => 1,
                                'order_id' => $order->id,
                                'order_type' => 4,
                                'expend_money' => $consumption_amount,
                                'surplus_money' => $residue_amount,
                            ];
                            //开始发短信
                            $sendMsg = new SendMsg();
                            $sendMsg->sendSMS($sendData);
                        }
                }

                //如果成交日期不是今天 修改保有代码
                if(!empty($request['deal_time']) && $request['deal_time'] != '0000-00-00' && $request['deal_time'] !== date('Y-m-d'))
                {
                    $logData = ['shop_id' => $request['shop_id'],'date' => $request['deal_time'],'create_time' => date('Y-m-d')];
                    Db::name('shop_retention_log')->insert($logData);
                }

                $this->error = '创建成功';

                return true;

            }else{
                throw new \Exception("出库单创建失败，请稍后再试");
            }

        } catch (\Exception $e) {

            Db::rollback();

            $this->error = $e->getMessage();

            return false;

        }

    }
    //获取消耗单次金额
    public function getRealCancelAmount($data){
        $cancel_balance = bcadd(0,$data['pay_amount'],2);
        $cancel_gift = bcadd(0,$data['gift_amount'],2);
        $discount_amount= bcadd(0,$data['discount_amount'],2);
        $num = $data['number'];
        if($num >1){
            $once_cancel_balance = bcdiv($cancel_balance,$num,2);
            $once_cancel_gift = bcdiv($cancel_gift,$num,2);
            $once_discount_amount = bcdiv($discount_amount,$num,2);
            $last_cancel_balance = bcsub($cancel_balance,bcmul(bcdiv($cancel_balance,$num,2),bcsub($num,1),2),2);
            $last_cancel_gift = bcsub($cancel_gift,bcmul(bcdiv($cancel_gift,$num,2),bcsub($num,1),2),2);
            $last_discount_amount = bcsub($discount_amount,bcmul(bcdiv($discount_amount,$num,2),bcsub($num,1),2),2);
        }else{
            $once_cancel_balance = $cancel_balance;
            $once_cancel_gift = $cancel_gift;
            $once_discount_amount =$discount_amount;
            $last_cancel_balance = 0;
            $last_cancel_gift = 0;
            $last_discount_amount = 0;
        }
        return [$once_cancel_balance,$once_cancel_gift,$last_cancel_balance,$last_cancel_gift,$once_discount_amount,$last_discount_amount];


    }

    //交过会费，然后调整账户
    public function sendCoupon($sendCoupon){
        $consumptionAll = $sendCoupon['consumptionAll'];
        // 入会即时发券 --------start---------
        $card_id = ['175','176','177','178','179','180','181','182','183','184'];
        $isSend = CouponProvideCustomer::where('customer_id',$sendCoupon['customer_id'])
            ->whereIn('coupon_id',$card_id)
            ->select()->toArray();
        $coupon = Coupon::whereIn('id',$card_id)->cache(3600)->column('start_time,end_time','id');
        if(empty($isSend)){
            $time = time();
            $cardList = array();
            if(floor($consumptionAll)>='5000' && floor($consumptionAll)<'15000'){
                array_push($cardList,'175','176');
            }elseif  (floor($consumptionAll)>='15000' && floor($consumptionAll)<'50000'){
                array_push($cardList,'177','178','179','180');
            }elseif (floor($consumptionAll)>='50000'){
                array_push($cardList,'181','182','183','184');
            }

            $provideCustomerList = array();
            foreach ($cardList as $k1 => $v1) {
                $provideCustomer = [];
                $provideCustomer['coupon_id'] = $v1;
                $provideCustomer['start_time'] = isset($coupon[$v1])?$coupon[$v1]['start_time']:0;
                $provideCustomer['end_time'] = isset($coupon[$v1])?$coupon[$v1]['end_time']:0;
                $provideCustomer['create_time'] = $time;
                $provideCustomer['customer_id'] = $sendCoupon['customer_id'];
                array_push($provideCustomerList,$provideCustomer);
            }
            CouponProvideCustomer::saveAll($provideCustomerList);
        }
        return true;
    }


    public function getCustomerBalance($balanceList,$bussiness_type=0){


        $bj = isset($balanceList[$bussiness_type]) ?$balanceList[$bussiness_type]['money']:0;
        $zj = isset($balanceList[$bussiness_type]) ?$balanceList[$bussiness_type]['complimentary_money']:0;
        $dz = isset($balanceList[$bussiness_type]) ?$balanceList[$bussiness_type]['shop_transfer_money']:0;

        return [$bj,$zj,$dz];
    }





    public function getMaxCustomerEnterShop($start_time,$end_time,$half_num,$month_max){
        $begin_year = date('Y',$start_time);
        $end_year = date('Y',$end_time);
        $year_diff = $end_year - $begin_year;
        $begin_month = date('m',$start_time);
        $end_month = date('m',$end_time);
        $month_diff = $end_month - $begin_month;

        $shou_yue_max_service_num = 0;
        $zhong_yue_max_service_num = 0;
        $end_yue_max_servcie_num = 0;

        if($month_diff == 0 && $begin_year == $end_year){ //同年同月份

            if($end_time -  $start_time <=(60*60*24*15)){
                $service_max_num = $half_num;
            }else{
                $service_max_num = $month_max;
            }
            $shou_yue_max_service_num = $service_max_num;
        }else if($month_diff == 1 && $begin_year == $end_year){ //同年相邻月份
            $begin_end_month_day = strtotime(date('Y-m-t',$start_time).'23:59:59');
            if($begin_end_month_day -  $start_time <=(60*60*24*15)){
                $begin_max_num = $half_num;
            }else{
                $begin_max_num = $month_max;
            }
            $shou_yue_max_service_num = $begin_max_num;
            $end_day = date('d',$end_time);
            if($end_day == 1){
                $end_max_num = 0;
            }else if(1<$end_day && $end_day<=15){
                $end_max_num = $half_num;
            }else{
                $end_max_num = $month_max;
            }
            $end_yue_max_servcie_num = $end_max_num;
            $service_max_num = $begin_max_num + $end_max_num;
        }else{

            if($begin_year == $end_year){

                $begin_end_month_day = strtotime(date('Y-m-t',$start_time).'23:59:59');
                if($begin_end_month_day - $start_time <=(60*60*24*15)){
                    $begin_max_num = $half_num;
                }else{
                    $begin_max_num = $month_max;
                }

                $shou_yue_max_service_num = $begin_max_num;
                $end_day = date('d',$end_time);
                if($end_day == 1){
                    $end_max_num = 0;
                }else if(1<$end_day && $end_day<=15){
                    $end_max_num = $half_num;
                }else{
                    $end_max_num = $month_max;
                }
                $end_yue_max_servcie_num = $end_max_num;
                $zhong_yue_max_service_num = $month_max;
                $service_max_num = $begin_max_num + $end_max_num +  (($month_diff-1) *$month_max);
            }else{

                //跨年年份
                $begin_diff = 12-$begin_month;
                $begin_max_num = 0;
                $begin_end_month_day = strtotime(date('Y-m-t',$start_time).'23:59:59');
                if($begin_end_month_day - $start_time <=(60*60*24*15)){
                    $begin_max_num = $half_num;
                }else{
                    $begin_max_num = $month_max;
                }
                $shou_yue_max_service_num = $begin_max_num;

                if($begin_diff>0){
                    $begin_max_num = $begin_max_num+($begin_diff*$month_max);
                    $zhong_yue_max_service_num = $month_max;
                }

                $end_diff = $end_month -1;

                $end_day = date('d',$end_time);

                if($end_day == 1){
                    $end_max_num = 0;
                }else if(1<=$end_day && $end_day<=15){
                    $end_max_num = $half_num;
                }else{
                    $end_max_num = $month_max;
                }
                $end_yue_max_servcie_num = $end_max_num;

                if($end_diff>0){
                    $end_max_num = $end_max_num+($end_diff*$month_max);
                    $zhong_yue_max_service_num = $month_max;
                }

                $service_max_num = $begin_max_num+$end_max_num;
                if($year_diff >1){
                    $service_max_num  = $service_max_num + (12*$month_max);
                    $zhong_yue_max_service_num = $month_max;
                }
            }

        }
        return ['service_max_num'=>$service_max_num,'shou'=>$shou_yue_max_service_num,'zhong'=>$zhong_yue_max_service_num,'wei'=>$end_yue_max_servcie_num];
    }





    /**
     * 修改订单状态
     * 审核、反审核、作废、确认收货
     * @param array $request 请求参数
     * @return bool
     * @author Liu
     * @create 2021-11-08
     */

    public function checkOrderData($request)
    {
        //出库单作废
        $id = $request['order_id'] ?? 0;
        $status = $request['status'] ?? 0;
        if (empty($id)) {
            throw new \Exception('参数错误');
        }

        // 订单作废
        if($status !== 4) {
            throw new \Exception('订单状态不正确');
        }
        try {
            $order = ShopOrderModel::lock(true)->where('id',$id)->find();

            if(!$order) {
                throw new \Exception('订单不存在');
            }
            //判断是否是核销记录产出的订单
            if($order->service_log_id >0){
                throw new \Exception('核销记录产出的订单，无法作废');
            }
            //是不是病例开单拆出来的单子
            if($order->case_order_id >0){
                throw new \Exception('病例-拆出来的单子，无法作废');
            }


            $goodList = ShopOrderGoods::where('order_id',$order['id'])->select()->toArray();

            $vipCard = 0;
            $is_have_prestock = 0; //是否有预存货
            $deduct_balance = $deduct_gift = [];//扣款本金、扣款赠金
            $project_ids = [];
            foreach ($goodList as $key => $val) {

                if(in_array($val['prestock_type'],[2,3])){
                    $is_have_prestock = 1;
                }

                if(in_array($val['prestock_type'],[1,2]) && $val['goods_id']!= 170){
                    //1不存货 2 存货
                    array_push($deduct_balance,$val['pay_amount']);
                    array_push($deduct_gift,$val['gift_amount']);

                }else if($val['prestock_type'] == 3){
                    //出货-需把对应的库存加回去
                    $prstock_exit =  CustomerPrestockExit::where('shop_order_goods_id',$val['id'])
                        ->where('type',1)->field('c_prestock_goods_id,num')->find();
                    if(!empty($prstock_exit)) {
                        $residue_prstock_num = CustomerPrestockGoods::where('id', $prstock_exit['c_prestock_goods_id'])->value('num');
                        if (empty($prstock_exit) || empty($residue_prstock_num)) {
                            throw new \Exception('预存信息不存在，请联系后台工作人员');
                        }
                        $update = [
                            'num' => bcadd($residue_prstock_num, $prstock_exit['num'], 2),
                            'update_time' => time(),
                        ];
                        $res = CustomerPrestockGoods::where('id', $prstock_exit['c_prestock_goods_id'])->update($update);
                        if (!$res) {
                            throw new \Exception('库存回库失败');
                        }
                    }
                }
            }

            if($is_have_prestock == 1){
                $c_prestock_goods = CustomerPrestockGoods::where('order_id',$order['id'])->field('is_use,id')->select()->toArray();
                $c_customer_prestock_goods_id = array_column($c_prestock_goods,'id');
                $exit = CustomerPrestockExit::whereIn('c_prestock_goods_id',$c_customer_prestock_goods_id)->count();
                if($exit>0){
                    throw new \Exception('预存货有产出记录，该订单无法作废');
                }

                $update['is_cancel'] = 1;
                $update['cancel_time'] = time();
                $update['cancel_operator_id'] = $request['operator_id']; //作废人
                CustomerPrestockGoods::whereIn('id',$c_customer_prestock_goods_id)->update($update);
            }

            $service_ids = Service::where('order_id',$id)->column('id');
            if(!empty($service_ids)){
                $service_logs = ServiceLog::whereIn('service_id',$service_ids)->where('is_cancel',0)->find();
                if(!empty($service_logs)){
                    throw new \Exception('卡项核销记录，该订单无法作废');
                }
                Service::where('order_id',$id)->update(['status'=>3]);//卡项提前结束
            }

            $arr = [0=>'待支付',1=>'已支付',2=>'已下推',3=>'已评价',4=>'已作废'];
            $content = '';
            $content .= '，状态：【' . $arr[$order['status']] . '】修改为【' . $arr[$status] . '】';
            $data['status'] = $status; // 订单状态： 订单状态：0.待支付 1.已支付 2.已下推 3.已评价 4.已取消
            $data['update_time'] = time();
            $bool = $this->where(['id'=>$id])->update($data);
            if(!$bool){
                throw new \Exception("操作失败，请稍后重试");
            }

            // 处理客户的余额 //
            $customerModel = new \app\crm\model\Customer();
            $customer_id   = $order['uid'];    // 客户的id
            $balanceData   = [                // 余额变更数据集
                'change_type'  => 1,      // 变动类型 1:增加 2:减少
                'change_balance'  => bcadd(0,array_sum($deduct_balance),2),
                'change_gift_balance'  => bcadd(0,array_sum($deduct_gift),2),
            ];
            $orderInfo     = [
                'customer_id'=>$customer_id,
                'order_id'=>$order['id'],
                'type'=>4,
                'notes'=>708,
                'remarks'=>'出货取消'
            ];
            $newOrderData  = [];
            $yhjOrderInfo  = [];

            $deal_time = date('Y-m-d',$order['deal_time']);
            $customerModel->processingFunds($customer_id,$balanceData,$deal_time,$newOrderData,$orderInfo,$yhjOrderInfo);

            // 添加操作记录

            $this->addActionRecord($request['operator_id'], 'shop_order_check', $id, $content, 'shop', 'order');


            $addLogModel = new AddOrderLog();
            $addLogModel->deletedData($customer_id,$order['order_no']);


            //如果成交日期不是今天 修改保有代码
            if(!empty($order['deal_time']) && $order['deal_time'] != '0000-00-00' && $order['deal_time'] !== date('Y-m-d'))
            {
                $logData = ['shop_id' => $order['shop_id'],'date' => date('Y-m-d', $order['deal_time']),'create_time' => date('Y-m-d')];
                Db::name('shop_retention_log')->insert($logData);
            }

            Db::commit();
            $this->error = '操作成功';
            return true;

        } catch (\Exception $e) {
            Db::rollback();
            $this->error = $e->getMessage();
            return false;
        }

    }

    //订单发生变化-根据定时任务进行调整
    public function clienShopAmountChange($order){
        $insert = [
            'market_id'=>$order['market_id'],
            'shop_id'=>$order['shop_id'],
            'customer_id'=>$order['customer_id'],
            'order_id'=>$order['order_id'],
            'order_type'=>$order['order_type'],
            'order_deal_time'=>$order['deal_time'],
            'create_time'=>time(),
            'remark'=>$order['remark'],
            'order_action'=>$order['order_action'],
            'type'=>$order['type'],
        ];
        DB::name('clientshop_change_amount_log')->insert($insert);

        return true;
    }

    /**

     * 生成订单号

     * @param  array $request 请求参数

     * @return String

     * @author SL

     * @create 2021-06-03

     */

    public function getOrderNo()

    {

        $order_sn = null;

        // 保证不会有重复订单号存在

        while(true){

            $order_sn = date('YmdHis').rand(1000,9999); // 订单编号

            $order_sn_count = DB::name('shop_order')->where('order_no', $order_sn)->count();

            if($order_sn_count == 0)

                break;

        }

        return $order_sn;

    }





    /**

     * 订单操作记录

     * @param  array $request 请求参数

     * @return array

     * @author SL

     * @create 2021-06-10 9:33

     */

    public function getOrderRecordList(array $request): array

    {

        $orderId = $request['order_id'] ?? 0;

        if (!$orderId) {

            $this->error = '参数错误';

            return [];

        }



        $page  = isset($request['page']) && intval($request['page']) ? intval($request['page']) : 1;

        $limit = isset($request['limit']) && intval($request['limit']) ? intval($request['limit']) : 15;

        return $this->getActionRecordListByPage($orderId, 'shop', 'order', 0, $page, $limit);

    }





    /**

     * 获取订单列表

     * @param  array $request 请求参数

     * @return array

     * @author SL

     * @create 2021-06-1

     */

    public function lcokOrderData($request)

    {

        try {

            $userId  = $request['user_id'] ?? 0;

            $shopIds= $request['shopIds'] ?? '';

            $request = $this->fmtRequest($request);

            $map     = $request['map'] ?? [];

            $where   = [];

            $uid      = isset($map['uid']) && $map['uid'] ? trim($map['uid']) : ''; // 会员id

            $shop_id      = isset($map['shop_id']) && $map['shop_id'] ? trim($map['shop_id']) : ''; // 门店id

            $noValue      = isset($map['no_value']) && $map['no_value'] ? trim($map['no_value']) : ''; // 单号

            $consignee = isset($map['consignee']) && $map['consignee'] ? trim($map['consignee']) : ''; // 客户名称

            $start_time = isset($map['start_time']) && $map['start_time'] ? strtotime(date($map['start_time'])) : 0;

            $end_time = isset($map['end_time']) && $map['end_time'] ? strtotime(date($map['end_time'] . ' 23:59:59')) : 0;

            $business_type    = isset($map['business_type']) && intval($map['business_type']) ? intval($map['business_type']) : 0; // 订单状态

            $order_type       = isset($map['order_type']) && intval($map['order_type']) ? intval($map['order_type']) : 0; // 订单状态

            $low_total = isset($map['low_total']) && $map['low_total'] ? $map['low_total']: 0;//销售金额区间搜索最小值

            $large_total =  isset($map['large_total']) && $map['large_total'] ? $map['large_total']: 0;//销售金额区间搜索最大值

            $shop_name = isset($map['shop_name']) && $map['shop_name'] ? trim($map['shop_name']) : ''; // 门店名称

            // 获取客户数据权限 的客户名称

            if ($shopIds)

            {

                array_push($where, ['shop_id', 'in', $shopIds]);

            }

            if ($uid)

            {

                //会员id搜索

                array_push($where, ['uid', '=', $uid]);

            }

            if ($shop_id)

            {

                //门店id搜索

                array_push($where, ['shop_id', '=', $shop_id]);

            }



            if ($shop_name)

            {

                //门店名称搜索

                array_push($where, ['shop_name', 'like', '%'.$shop_name.'%']);

            }

            if ($consignee) {

                // 客户名称搜索

                array_push($where, ['consignee', 'like', '%'.$consignee.'%']);

            }

            if ($noValue) {

                array_push($where, ['order_no', '=', $noValue]);

            }





            // 时间

            if($start_time && $end_time)

            {

                array_push($where, ['deal_time', 'between', "$start_time,$end_time"]);

            }



            if ($business_type)

            {

                //业务类型搜索

                array_push($where, ['business_type', '=', $business_type]);

            }

            if ($order_type)

            {

                //订单类型搜索

                array_push($where, ['order_type', '=', $order_type]);

            }



            if ($low_total && !$large_total)

            {

                array_push($where, ['order_amount', 'egt', $low_total]);

            }

            if (!$low_total && $large_total)

            {

                array_push($where, ['order_amount', 'elt', $large_total]);

            }

            if ($low_total && $large_total)

            {

                array_push($where, ['order_amount', 'between', "$low_total,$large_total"]);

            }

            $sqlQuery = $this->where($where);

            $dataCount  = $sqlQuery->count();

            $bool=0;

            if ($dataCount) {

                $bool = $sqlQuery->update(['is_lock' => 1]);

            }

            $this->error = '锁定成功'.$bool.'单';

            $data              = [];

            $data['dataCount'] = $bool ?? 0;

            return $data;

        } catch (\Exception $e) {

            $this->error = $e->getMessage();

            return [];

        }

    }









}

